<template>
    <div
        style="margin-right: 20px;width: 300px;display: flex;justify-content: center;flex-direction: column; align-items: center;">

        <Cropper :layer="layer" v-model="img" />
        <el-button @click="showWindow" tabindex="0" class="cover-upload-btn">
            <div v-if="!img">+<br />
                <div style="font-size: small;color :gray">添加课程封面</div>
            </div>

            <img v-if="img" :src="img" style="width: 150px; height: 150px; border-radius: 5%;">
        </el-button>
    </div>
</template>

<script lang="ts" setup>
import { ref, watch, reactive, onMounted } from 'vue'
import Cropper from '@/components/cropper/index.vue'
import { compressImage } from "@/utils/compressImage"
const emit = defineEmits(['update:modelValue'])
const layer = reactive({
    show: false,
    title: '图片上传'
})

const img = ref(null)

function showWindow() {
    layer.show = true
}
watch(img, (newValue, oldValue) => {
    // 在属性改变时执行的函数
    console.log("新图片大小", (newValue.length / 1024 / 1024).toFixed(2) + 'MB')
    if (parseInt((newValue.length / 1024 / 1024).toFixed(2)) > 2) {
        img.value = compressImage(img).value
    }
    emit('update:modelValue', img.value)
})
// 在这里执行其他逻辑
onMounted(() => {
    img.value = history.state.cover || ''
})
</script>

<style lang="scss" scoped>
.cover-upload-btn {
    font-size: 20px;
    width: 150px;
    height: 150px;
    margin-top: 20px;
    background-color: #f2f3f5;
    border-radius: 5px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
}
</style>